
var server = require('./utils/server');
var md5 = require('./utils/md5.js');

// 授权登录 
App({
	onLaunch: function () {
		// auto login via SDK
		var that = this;
		//AV.User.loginWithWeapp();


		// 设备信息
		wx.getSystemInfo({
			success: function (res) {
				that.screenWidth = res.windowWidth;
				that.pixelRatio = res.pixelRatio;
			}
		});

    // that.getUserInfo();
	},
  getAuth:function(e){
    var ap = this;
    ap.getOpenId(e);
  },
	getOpenId: function (cb) {
    var appjs = this;
    appjs.globalData.auth = true;
    wx.login({
            success: function (res) {
              console.log(res)
              if (res.code) {
                //发起网络请求
                wx.request({
                  url: 'https://www.donglongshangcheng.com/index.php/wxapi/User/sendappid?appid=wx16ae89fc61a5651c&secret=397b0a9a44b8f8aa976dced58e15cc91&js_code=' + res.code + '&grant_type=authorization_code',
                  data: {
                    code: res.code
                  },
                  success: function (response) {
                    // 获取openId
                    var openId = response.data.openid.openid;
                    var unionid = response.data.openid.unionid;
                    var sysinfo = wx.setStorageSync('sysinfo', response.data.openid)
                    // TODO 缓存 openId
                    var app = getApp();
                    var that = app;
                    that.globalData.openid = openId;
                    that.globalData.unionid = unionid;
                    //验证是否关联openid

                    // typeof cb == "function" && cb()
                    // var unionid = getApp().globalData.unionid;
                    console.log(cb)
                    server.getJSON("/User/validateOpenid", { unionid: unionid, info: JSON.stringify(cb), opneid: openId}, function (res) {
                      console.log(res)
                      if (res.data.code == 200) {
                        getApp().globalData.login = true;
                        getApp().globalData.userInfo = res.data.data;
                        if (res.data.data.mobile == "" || res.data.data.mobile == null){
                          wx.navigateTo({
                            url: '/pages/register/index',
                          })
                        }else{
                          console.log("手机号已绑定")
                          getApp().globalData.isband = true;
                          console.log(getApp().globalData.isband)
                        }
                      } else {
                        if (res.data.code == '400') {
                          getApp().globalData.login = true;
                          console.log("need register");
                          app.register(function () {
                          });
                        }
                      }
                    });

                  }
                })
              } else {
                console.log('获取用户登录态失败！' + res.errMsg)
              }
            }
          });
	},

	register:function(cb){
     var app = this;
       this.getUserInfo(function () {
         var openId = app.globalData.openid;
         var unionid = app.globalData.unionid;
            var userInfo = app.globalData.userInfo;
            var country = userInfo.country;
            var city = userInfo.city;
            var gender = userInfo.gender;
            var nick_name =  userInfo.nickName;
            var province = userInfo.province;
            var avatarUrl = userInfo.avatarUrl;
            var first_leader = getApp().globalData.first_leader;


         server.getJSON('/User/register?open_id=' + openId + "&country=" + country + "&gender=" + gender + "&nick_name=" + nick_name + "&province=" + province + "&unionid=" + unionid + "&city=" + city + "&head_pic=" + avatarUrl + "&first_leader=" + first_leader,function(res){
           console.log(res)
app.globalData.userInfo = res.data.res
                // typeof cb == "function" && cb()
           if (res.data.res.mobile == "" && res.data.res.email == "") {
             wx.navigateTo({
               url: '/pages/register/index',
             })
           }
						});

       })
  },
getUserInfo:function(cb){
    var that = this
    if(this.globalData.userInfo){
      typeof cb == "function" && cb(this.globalData.userInfo)
    }else{
      //调用登录接口
      wx.login({
        success: function () {
          wx.getUserInfo({
            success: function (res) {
              that.globalData.userInfo = res.userInfo
              typeof cb == "function" && cb(that.globalData.userInfo)
            }
          })
        }
      })
    }
  },

  isLogin:function(){
    var user_id = getApp().globalData.userInfo;
    var is_login = getApp().globalData.login
    var sysinfo = wx.getStorageSync("sysinfo");
    console.log(sysinfo)
    console.log(typeof(sysinfo))
      if(user_id == null || sysinfo == undefined || sysinfo == '' || !is_login){
          getApp().getAuth();
      }
  },

  isBindPhone:function(e){
    var info = getApp().globalData.userInfo;
    if(info.mobile == "" || info.mobile == null){
      getApp().globalData.isband = false;
      wx.showToast({
        title: '请先绑定手机号',
        icon:'none'
      })
      setTimeout(function(){
        wx.navigateTo({
          url: "/pages/register/index"
        })        
      },500)
      return;
    }else{
      getApp().globalData.isband = true;
    }
  },

	globalData: {
		'openid': null,
		'userInfo':null,
		'login':false,
    'unionid':null,
    'auth':false,
    'isband':false,
    'first_leader':0,
	}
})
